import styles from './index.module.scss'
import { useEffect, useState, useRef } from 'react'
import Input from './input'
import Button from '../button'
import { checkEmailExist } from '@/api/login'

const Index = props => {
  const { setType, email, setEmail } = props
  const [showEmailError, setEmailError] = useState(false)
  const submitRef = useRef(null)
  const inputRef = useRef(null)
  const checkEmail = email => {
    const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ //优化邮箱校验
    return pattern.test(email)
  }
  const nextStep = async () => {
    const isPass = checkEmail(email)
    setEmailError(!isPass)
    if (!isPass) {
      return
    }
    const res = await checkEmailExist(email)
    setType(res.data.exist ? 'enter_pwd' : 'sign_in')
  }

  useEffect(() => {
    const enterClick = e => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    inputRef.current.focus()
    window.addEventListener('keydown', enterClick)
    return () => {
      window.removeEventListener('keydown', enterClick)
    }
  }, [])
  return (
    <div className={styles.enterEmail}>
      <Input placeholder="请输入您的邮箱" ref={inputRef} onChange={data => setEmail(data.trim())} />
      {showEmailError ? <p className={styles.errorInfo}>请输入正确格式的邮箱</p> : null}
      <p className={styles.tip}>若该邮箱首次登录，系统会帮您先创建账号</p>
      <Button hover="opacity" ref={submitRef} onClick={nextStep} className={styles.btn}>
        下一步
      </Button>
    </div>
  )
}

export default Index
